package com.zhengshang.quartz.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.zhengshang.api.domain.AppTaoOrder;
import com.zhengshang.api.domain.AppTaoRelation;
import com.zhengshang.api.service.IAppTaoOrderService;
import com.zhengshang.api.service.IAppTaoRelationService;
import com.zhengshang.common.constant.app.AppConstant;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.utils.DateUtils;
import com.zhengshang.common.utils.StringUtils;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.system.service.ISysUserService;
import com.zhengshang.third.taobao.TaoBaoUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 淘宝订单调度测试
 *
 * @author ruoyi
 */
@Component("taobaoOrderTask")
public class TaobaoOrderTask {

    protected final Logger logger = LoggerFactory.getLogger(TaobaoOrderTask.class);

    @Autowired
    private TaoBaoUtils taoBaoUtils;

    @Autowired
    private IAppTaoOrderService appTaoOrderService;

    @Autowired
    private IAppTaoRelationService appTaoRelationService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 递归查询接口数据
     *
     * @param hasPre
     * @param positionIndex
     * @param endTime
     * @param startTime
     * @param pageNo
     */
    private void syscTaobaoCreateOrder(Boolean hasPre, String positionIndex, String endTime, String startTime, Integer pageNo) {
        if (hasPre) {
            AjaxResult ajaxResult = taoBaoUtils.queryOrderList(1, positionIndex, pageNo, 50, 2, "", endTime, startTime, -1, 3);
            Integer code = TypeUtils.castToInt(ajaxResult.get("code"));
            if (code == 200) {
                JSONObject data = (JSONObject) ajaxResult.get("data");
                hasPre = data.getBoolean("has_pre");
                positionIndex = data.getString("position_index");
                String results = data.getString("results");
                Object object = JSON.parse(results);
                if (object instanceof JSONObject) {
                    //说明有数据
                    JSONObject jsonObject = (JSONObject) object;
                    String publisherOrderDto = jsonObject.getString("publisher_order_dto");
                    //String publisherOrderDto = "{\"tk_paid_time\":\"2022-05-01 11:03:37\",\"alipay_total_price\":\"4.00\",\"marketing_type\":\"\",\"seller_shop_title\":\"丞昌旗舰店\",\"trade_id\":\"2606511207040857813\",\"click_time\":\"2022-05-01 10:51:39\",\"subsidy_rate\":\"0.00\",\"item_title\":\"搭配马丁靴的裤子春季高级感英伦雅痞风男装炸街西裤九分束脚哈伦\",\"order_type\":\"天猫\",\"tk_order_role\":2,\"pub_id\":1736970083,\"item_img\":\"//img.alicdn.com/tfscom/i1/2212343608723/O1CN01OKHluW2EJBal5KfO3_!!2212343608723.png\",\"tb_deposit_time\":\"--\",\"total_commission_rate\":\"4.50\",\"trade_parent_id\":\"2606511207040857813\",\"subsidy_type\":\"--\",\"tk_create_time\":\"2022-05-01 10:52:01\",\"site_name\":\"油惠牛\",\"tk_commission_rate_for_media_platform\":\"0.00\",\"tk_deposit_time\":\"--\",\"tk_total_rate\":\"4.50\",\"adzone_name\":\"线上推广\",\"site_id\":2296150409,\"is_lx\":\"0\",\"flow_source\":\"--\",\"tk_commission_pre_fee_for_media_platform\":\"0.00\",\"terminal_type\":\"无线\",\"item_category_name\":\"男装\",\"adzone_id\":112049900165,\"alimama_share_fee\":\"0.00\",\"modified_time\":\"2022-05-01 11:03:55\",\"refund_tag\":0,\"tb_paid_time\":\"2022-05-01 11:03:25\",\"total_commission_fee\":\"0.00\",\"alimama_rate\":\"0.00\",\"item_id\":669256155086,\"special_id\":2833436787,\"item_price\":\"210.00\",\"tk_status\":13,\"pub_share_fee\":\"0.00\",\"item_num\":1,\"tk_commission_fee_for_media_platform\":\"0.00\",\"income_rate\":\"4.50\",\"pub_share_pre_fee\":\"0.18\",\"app_key\":\"24663869\",\"pub_share_rate\":\"100.00\",\"item_link\":\"http://item.taobao.com/item.htm?id=669256155086\",\"deposit_price\":\"0.00\",\"seller_nick\":\"丞昌旗舰店\",\"subsidy_fee\":\"0.00\"}";
                    List<AppTaoOrder> appTaoOrderList = JSON.parseArray(publisherOrderDto, AppTaoOrder.class);
                    for (AppTaoOrder appTaoOrder : appTaoOrderList) {
                        String tradeId = appTaoOrder.getTradeId();
                        Long specialId = appTaoOrder.getSpecialId();
                        int count = appTaoOrderService.countByTradeId(tradeId);
                        if (count == 0) {
                            AppTaoRelation appTaoRelation = appTaoRelationService.findBySpecialId(specialId);
                            appTaoOrder.setIsCommission(0);
                            if (StringUtils.isNotNull(appTaoRelation)) {
                                Long userId = appTaoRelation.getUserId();
                                appTaoOrder.setUserId(userId);
                            }
                            appTaoOrderService.insertAppTaoOrder(appTaoOrder);
                        }
                    }
                    if (hasPre) {
                        syscTaobaoCreateOrder(hasPre, positionIndex, endTime, startTime, pageNo + 1);
                    }
                }
            }
        }
    }

    /**
     * 同步淘宝订单入库,注意数据去重
     * 1、按照订单创建时间获取会员订单---利用接口一
     * 每隔2分钟调用1次订单接口，获取最近5分钟或者10分钟内的订单创建数据，注意数据去重。获取的数据中包含全部订单付款订单和大部分失效订单
     */
    public void syscTaobaoCreateOrderToDateBase() {
        Date endDateTime = DateUtils.getNowDate();
        Date startDateTime = DateUtils.addMin(endDateTime, -20);
        String endTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", endDateTime);
        String startTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", startDateTime);
        syscTaobaoCreateOrder(true, "", endTime, startTime, 1);
    }


    /**
     * 递归查询接口数据
     *
     * @param hasPre
     * @param positionIndex
     * @param endTime
     * @param startTime
     * @param pageNo
     */
    private void syscTaobaoSettleOrder(Boolean hasPre, String positionIndex, String endTime, String startTime, Integer pageNo) {
        if (hasPre) {
            String rate = sysConfigService.selectConfigByKey("app.thirdorder.commission.rate");
            BigDecimal commissionRate = new BigDecimal(rate).divide(new BigDecimal(100));
            AjaxResult ajaxResult = taoBaoUtils.queryOrderList(3, positionIndex, pageNo, 50, 2, "", endTime, startTime, -1, 3);
            Integer code = TypeUtils.castToInt(ajaxResult.get("code"));
            if (code == 200) {
                JSONObject data = (JSONObject) ajaxResult.get("data");
                hasPre = data.getBoolean("has_pre");
                positionIndex = data.getString("position_index");
                String results = data.getString("results");
                Object object = JSON.parse(results);
                if (object instanceof JSONObject) {
                    JSONObject jsonObject = (JSONObject) object;
                    String publisherOrderDto = jsonObject.getString("publisher_order_dto");
                    List<AppTaoOrder> appTaoOrderList = JSON.parseArray(publisherOrderDto, AppTaoOrder.class);
                    for (AppTaoOrder appTaoOrder : appTaoOrderList) {
                        String tradeId = appTaoOrder.getTradeId();
                        Long userId = appTaoOrder.getUserId();
                        int count = appTaoOrderService.countByTradeId(tradeId);
                        if (count == 0) {
                            appTaoOrderService.insertAppTaoOrder(appTaoOrder);
                        } else {
                            //更新订单信息
                            AppTaoOrder taoOrder = appTaoOrderService.findByTradeId(tradeId);
                            Integer isCommission = taoOrder.getIsCommission();
                            String payPrice = taoOrder.getPayPrice();
                            BigDecimal payAmount = new BigDecimal(payPrice);
                            String itemTitle = taoOrder.getItemTitle();
                            if (isCommission == 0) {
                                appTaoOrder.setTaoId(taoOrder.getTaoId());
                                appTaoOrder.setUserId(taoOrder.getUserId());
                                appTaoOrder.setIsCommission(taoOrder.getIsCommission());
                                appTaoOrder.setRefundTag("1");
                                appTaoOrder.setCommissionAmount(taoOrder.getCommissionAmount());
                                //1.查询是否有上级
                                SysUser sysUser = sysUserService.selectUserById(userId);
                                appTaoOrder.setIsCommission(1);
                                if (StringUtils.isNotNull(sysUser)) {
                                    //上级Id
                                    Long upUserId = sysUser.getUpUserId();
                                    //上级账户
                                    SysUser upUser = sysUserService.selectUserById(upUserId);
                                    BigDecimal commissionAmount = payAmount.multiply(commissionRate);
                                    appTaoOrder.setCommissionAmount(commissionAmount);
                                    if (ObjectUtils.isNotEmpty(upUser)) {
                                        sysUserService.updateTwoUserBalance(sysUser, commissionAmount, itemTitle);
                                    }
                                } else {
                                    appTaoOrder.setCommissionAmount(BigDecimal.ZERO);
                                }
                                appTaoOrderService.updateAppTaoOrder(appTaoOrder);
                            }
                        }
                    }
                }
            }
            if (hasPre) {
                syscTaobaoCreateOrder(hasPre, positionIndex, endTime, startTime, pageNo + 1);
            }
        }
    }

    /**
     * 同步淘宝订单入库,注意数据去重
     * 1、按照订单创建时间获取会员订单---利用接口一
     * 每隔2分钟调用1次订单接口，获取最近5分钟或者10分钟内的订单结算数据，注意数据去重。获取的数据中包含全部订单付款订单和大部分失效订单
     */
    public void syscTaobaoSettleOrderToDateBase() {
        Date endDateTime = DateUtils.getNowDate();
        Date startDateTime = DateUtils.addMin(endDateTime, -20);
        String endTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", endDateTime);
        String startTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", startDateTime);
        syscTaobaoSettleOrder(true, "", endTime, startTime, 1);
    }

    public static void main(String[] args) {
        String yesterDay = DateUtils.getYesterDay() + " 00:00:00";
        String todayDay = DateUtils.getDate() + " 00:00:00";
        Date date = DateUtils.parseDate(yesterDay);
        int minutes = 30;
        List<String> list = Lists.newArrayList();
        for (int i = 0; i < 48; i++) {
            Date date2 = DateUtils.addMin(date, i * minutes);
            String dateStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", date2);
            list.add(dateStr);
        }
        list.add(todayDay);
        for (int i = 0; i < list.size(); i++) {
            int j = i + 1;
            if (j < list.size()) {
                String dateStr = list.get(i);
                String dateStr1 = list.get(i + 1);
                System.out.println(dateStr + "----------------" + dateStr1);
            }

        }
    }
}
